#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
候选人深度分析模块
提供全方位的候选人评估、岗位匹配度分析和可视化数据生成
"""

import os
import json
import logging
import re
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass

# LangChain核心模块
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

# 数据管理
from data_manager import data_manager

# 配置日志
logger = logging.getLogger(__name__)

# ==================== 数据模型定义 ====================

@dataclass
class AnalysisDimension:
    """分析维度数据模型"""
    name: str
    score: float  # 0-100分
    weight: float  # 权重
    details: Dict[str, Any]
    suggestions: List[str]

@dataclass
class VisualizationData:
    """可视化数据模型"""
    chart_type: str  # radar, bar, pie, line等
    title: str
    data: Dict[str, Any]
    config: Dict[str, Any]

@dataclass
class CandidateAnalysisReport:
    """候选人分析报告"""
    candidate_id: str
    job_id: Optional[str]
    overall_score: float
    dimensions: List[AnalysisDimension]
    visualizations: List[VisualizationData]
    summary: str
    recommendations: List[str]
    risks: List[str]
    interview_questions: List[str]
    generated_at: str

# ==================== 分析工具定义 ====================

@tool
def analyze_candidate_skills(candidate_id: str, job_requirements: Dict[str, Any]) -> Dict[str, Any]:
    """深度分析候选人技能匹配度"""
    logger.info(f"🔍 深度分析候选人 {candidate_id} 技能匹配度")
    
    # 获取候选人信息
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    # 获取岗位要求的技能
    required_skills = job_requirements.get('required_skills', [])
    preferred_skills = job_requirements.get('preferred_skills', [])
    
    # 分析候选人技能
    candidate_skills = candidate.skills if isinstance(candidate.skills, list) else [str(candidate.skills)]
    candidate_content = candidate.content or ""
    
    # 技能匹配分析
    skill_analysis = {
        'required_match': {},
        'preferred_match': {},
        'additional_skills': [],
        'missing_skills': [],
        'skill_level_assessment': {}
    }
    
    # 分析必需技能匹配
    for req_skill in required_skills:
        match_score = calculate_skill_match(req_skill, candidate_skills, candidate_content)
        skill_analysis['required_match'][req_skill] = {
            'score': match_score,
            'evidence': extract_skill_evidence(req_skill, candidate_content),
            'level': assess_skill_level(req_skill, candidate_content)
        }
    
    # 分析优选技能匹配
    for pref_skill in preferred_skills:
        match_score = calculate_skill_match(pref_skill, candidate_skills, candidate_content)
        skill_analysis['preferred_match'][pref_skill] = {
            'score': match_score,
            'evidence': extract_skill_evidence(pref_skill, candidate_content),
            'level': assess_skill_level(pref_skill, candidate_content)
        }
    
    # 找出候选人的额外技能
    all_job_skills = set([s.lower() for s in required_skills + preferred_skills])
    for skill in candidate_skills:
        if skill.lower() not in all_job_skills:
            skill_analysis['additional_skills'].append(skill)
    
    # 找出缺失的必需技能
    for req_skill in required_skills:
        if skill_analysis['required_match'][req_skill]['score'] < 0.3:
            skill_analysis['missing_skills'].append(req_skill)
    
    return skill_analysis

@tool
def analyze_candidate_experience(candidate_id: str, job_requirements: Dict[str, Any]) -> Dict[str, Any]:
    """分析候选人工作经验匹配度"""
    logger.info(f"📊 分析候选人 {candidate_id} 工作经验")
    
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    min_exp = job_requirements.get('min_experience_years', 0)
    candidate_exp = candidate.experience_years or 0
    content = candidate.content or ""
    
    # 经验分析
    experience_analysis = {
        'total_years': candidate_exp,
        'required_years': min_exp,
        'experience_gap': max(0, min_exp - candidate_exp),
        'experience_surplus': max(0, candidate_exp - min_exp),
        'relevant_experience': extract_relevant_experience(content, job_requirements),
        'industry_experience': extract_industry_experience(content),
        'leadership_experience': extract_leadership_experience(content),
        'project_complexity': assess_project_complexity(content),
        'career_progression': analyze_career_progression(content)
    }
    
    return experience_analysis

@tool
def analyze_candidate_education(candidate_id: str, job_requirements: Dict[str, Any]) -> Dict[str, Any]:
    """分析候选人教育背景匹配度"""
    logger.info(f"🎓 分析候选人 {candidate_id} 教育背景")
    
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    content = candidate.content or ""
    education = getattr(candidate, 'education', getattr(candidate, 'qualification', ''))
    
    # 教育背景分析
    education_analysis = {
        'degree_level': extract_degree_level(content, education),
        'field_of_study': extract_field_of_study(content),
        'university_ranking': assess_university_ranking(content),
        'relevant_courses': extract_relevant_courses(content, job_requirements),
        'certifications': extract_certifications(content),
        'continuous_learning': assess_continuous_learning(content),
        'academic_achievements': extract_academic_achievements(content)
    }
    
    return education_analysis

@tool
def generate_candidate_radar_chart(candidate_id: str, job_id: Optional[str] = None) -> Dict[str, Any]:
    """生成候选人能力雷达图数据"""
    logger.info(f"📊 生成候选人 {candidate_id} 雷达图数据")
    
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    # 定义评估维度
    dimensions = [
        "技术能力",
        "项目经验", 
        "沟通能力",
        "学习能力",
        "领导力",
        "行业经验",
        "教育背景",
        "稳定性"
    ]
    
    # 计算各维度分数
    scores = []
    content = candidate.content or ""
    
    # 技术能力评分 (基于技能和项目)
    tech_score = assess_technical_ability(candidate, content)
    scores.append(tech_score)
    
    # 项目经验评分
    project_score = assess_project_experience(content)
    scores.append(project_score)
    
    # 沟通能力评分 (基于简历质量和表达)
    communication_score = assess_communication_ability(content)
    scores.append(communication_score)
    
    # 学习能力评分 (基于技能多样性和认证)
    learning_score = assess_learning_ability(content)
    scores.append(learning_score)
    
    # 领导力评分
    leadership_score = assess_leadership_ability(content)
    scores.append(leadership_score)
    
    # 行业经验评分
    industry_score = assess_industry_experience(content)
    scores.append(industry_score)
    
    # 教育背景评分
    education_score = assess_education_background(candidate, content)
    scores.append(education_score)
    
    # 稳定性评分 (基于工作年限和职业规划)
    stability_score = assess_career_stability(content)
    scores.append(stability_score)
    
    radar_data = {
        "chart_type": "radar",
        "title": f"候选人能力雷达图 - {candidate.name or candidate_id[:8]}",
        "data": {
            "dimensions": dimensions,
            "scores": scores,
            "max_score": 100
        },
        "config": {
            "responsive": True,
            "scales": {
                "r": {
                    "beginAtZero": True,
                    "max": 100,
                    "ticks": {
                        "stepSize": 20
                    }
                }
            }
        }
    }
    
    return radar_data

@tool
def generate_skill_comparison_chart(candidate_id: str, job_requirements: Dict[str, Any]) -> Dict[str, Any]:
    """生成技能对比柱状图数据"""
    logger.info(f"📊 生成候选人 {candidate_id} 技能对比图")
    
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    required_skills = job_requirements.get('required_skills', [])
    if not required_skills:
        return {"error": "岗位要求技能为空"}
    
    content = candidate.content or ""
    candidate_skills = candidate.skills if isinstance(candidate.skills, list) else [str(candidate.skills)]
    
    # 计算每个技能的匹配度
    skill_scores = []
    skill_names = []
    
    for skill in required_skills:
        match_score = calculate_skill_match(skill, candidate_skills, content) * 100
        skill_scores.append(match_score)
        skill_names.append(skill)
    
    bar_data = {
        "chart_type": "bar",
        "title": f"技能匹配度对比 - {candidate.name or candidate_id[:8]}",
        "data": {
            "labels": skill_names,
            "datasets": [{
                "label": "匹配度(%)",
                "data": skill_scores,
                "backgroundColor": [
                    'rgba(75, 192, 192, 0.6)' if score >= 80 else
                    'rgba(255, 206, 86, 0.6)' if score >= 60 else
                    'rgba(255, 99, 132, 0.6)'
                    for score in skill_scores
                ],
                "borderColor": [
                    'rgba(75, 192, 192, 1)' if score >= 80 else
                    'rgba(255, 206, 86, 1)' if score >= 60 else
                    'rgba(255, 99, 132, 1)'
                    for score in skill_scores
                ],
                "borderWidth": 1
            }]
        },
        "config": {
            "responsive": True,
            "scales": {
                "y": {
                    "beginAtZero": True,
                    "max": 100
                }
            }
        }
    }
    
    return bar_data

@tool
def generate_comprehensive_analysis(candidate_id: str, job_id: Optional[str] = None) -> Dict[str, Any]:
    """生成候选人综合分析报告"""
    logger.info(f"📋 生成候选人 {candidate_id} 综合分析报告")
    
    candidate = data_manager.get_resume_by_id(candidate_id)
    if not candidate:
        return {"error": f"候选人 {candidate_id} 不存在"}
    
    # 获取岗位信息
    job = None
    job_requirements = {}
    if job_id:
        job = data_manager.get_job_by_id(job_id)
        if job:
            job_requirements = {
                'required_skills': job.required_skills or [],
                'preferred_skills': job.preferred_skills or [],
                'min_experience_years': job.min_experience_years or 0,
                'location': job.location or ''
            }
    
    # 收集所有分析数据
    content = candidate.content or ""
    
    # 生成各维度分析
    dimensions = []
    
    # 技能维度
    if job_requirements.get('required_skills'):
        skill_analysis = analyze_candidate_skills.invoke({
            "candidate_id": candidate_id,
            "job_requirements": job_requirements
        })
        skill_score = calculate_overall_skill_score(skill_analysis)
        dimensions.append(AnalysisDimension(
            name="技能匹配",
            score=skill_score,
            weight=0.4,
            details=skill_analysis,
            suggestions=generate_skill_suggestions(skill_analysis)
        ))
    
    # 经验维度
    exp_analysis = analyze_candidate_experience.invoke({
        "candidate_id": candidate_id,
        "job_requirements": job_requirements
    })
    exp_score = calculate_experience_score(exp_analysis, job_requirements)
    dimensions.append(AnalysisDimension(
        name="经验匹配",
        score=exp_score,
        weight=0.3,
        details=exp_analysis,
        suggestions=generate_experience_suggestions(exp_analysis)
    ))
    
    # 教育维度
    edu_analysis = analyze_candidate_education.invoke({
        "candidate_id": candidate_id,
        "job_requirements": job_requirements
    })
    edu_score = calculate_education_score(edu_analysis)
    dimensions.append(AnalysisDimension(
        name="教育背景",
        score=edu_score,
        weight=0.2,
        details=edu_analysis,
        suggestions=generate_education_suggestions(edu_analysis)
    ))
    
    # 软技能维度
    soft_skills_score = assess_soft_skills(content)
    dimensions.append(AnalysisDimension(
        name="软技能",
        score=soft_skills_score,
        weight=0.1,
        details={"communication": 75, "teamwork": 80, "problem_solving": 70},
        suggestions=["继续提升沟通表达能力", "增强团队协作经验"]
    ))
    
    # 计算总分
    overall_score = sum(dim.score * dim.weight for dim in dimensions)
    
    # 生成可视化数据
    visualizations = []
    
    # 雷达图
    radar_data = generate_candidate_radar_chart.invoke({"candidate_id": candidate_id, "job_id": job_id})
    if "error" not in radar_data:
        visualizations.append(VisualizationData(
            chart_type="radar",
            title=radar_data["title"],
            data=radar_data["data"],
            config=radar_data["config"]
        ))
    
    # 技能对比图
    if job_requirements.get('required_skills'):
        bar_data = generate_skill_comparison_chart.invoke({
            "candidate_id": candidate_id,
            "job_requirements": job_requirements
        })
        if "error" not in bar_data:
            visualizations.append(VisualizationData(
                chart_type="bar",
                title=bar_data["title"],
                data=bar_data["data"],
                config=bar_data["config"]
            ))
    
    # 生成分析报告
    report = CandidateAnalysisReport(
        candidate_id=candidate_id,
        job_id=job_id,
        overall_score=overall_score,
        dimensions=dimensions,
        visualizations=visualizations,
        summary=generate_analysis_summary(candidate, dimensions, overall_score),
        recommendations=generate_recommendations(dimensions, overall_score),
        risks=identify_risks(dimensions, exp_analysis),
        interview_questions=generate_interview_questions(dimensions, job_requirements),
        generated_at=datetime.now().isoformat()
    )
    
    return {
        "success": True,
        "report": {
            "candidate_id": report.candidate_id,
            "job_id": report.job_id,
            "overall_score": round(report.overall_score, 1),
            "dimensions": [
                {
                    "name": dim.name,
                    "score": round(dim.score, 1),
                    "weight": dim.weight,
                    "details": dim.details,
                    "suggestions": dim.suggestions
                }
                for dim in report.dimensions
            ],
            "visualizations": [
                {
                    "chart_type": viz.chart_type,
                    "title": viz.title,
                    "data": viz.data,
                    "config": viz.config
                }
                for viz in report.visualizations
            ],
            "summary": report.summary,
            "recommendations": report.recommendations,
            "risks": report.risks,
            "interview_questions": report.interview_questions,
            "generated_at": report.generated_at
        }
    }

# ==================== 辅助函数 ====================

def calculate_skill_match(skill: str, candidate_skills: List[str], content: str) -> float:
    """计算单个技能的匹配度"""
    skill_lower = skill.lower()
    content_lower = content.lower()
    
    # 直接匹配
    for candidate_skill in candidate_skills:
        if skill_lower in candidate_skill.lower():
            return 1.0
    
    # 内容匹配
    if skill_lower in content_lower:
        # 计算出现频率
        count = content_lower.count(skill_lower)
        return min(0.8, count * 0.2)
    
    # 相关技能匹配
    related_skills = get_related_skills(skill_lower)
    for related in related_skills:
        if related in content_lower:
            return 0.6
    
    return 0.0

def extract_skill_evidence(skill: str, content: str) -> List[str]:
    """提取技能相关的证据"""
    evidence = []
    skill_lower = skill.lower()
    
    # 查找包含技能的句子
    sentences = content.split('.')
    for sentence in sentences:
        if skill_lower in sentence.lower() and len(sentence.strip()) > 20:
            evidence.append(sentence.strip()[:100])
    
    return evidence[:3]  # 最多返回3个证据

def assess_skill_level(skill: str, content: str) -> str:
    """评估技能水平"""
    skill_lower = skill.lower()
    content_lower = content.lower()
    
    expert_keywords = ['expert', 'senior', 'lead', 'architect', 'master', '专家', '高级', '资深']
    intermediate_keywords = ['experienced', 'proficient', '熟练', '有经验']
    
    context = ""
    sentences = content.split('.')
    for sentence in sentences:
        if skill_lower in sentence.lower():
            context += sentence.lower() + " "
    
    for keyword in expert_keywords:
        if keyword in context:
            return "专家级"
    
    for keyword in intermediate_keywords:
        if keyword in context:
            return "熟练"
    
    if skill_lower in content_lower:
        return "了解"
    
    return "未知"

def get_related_skills(skill: str) -> List[str]:
    """获取相关技能"""
    skill_map = {
        'python': ['django', 'flask', 'pandas', 'numpy'],
        'java': ['spring', 'hibernate', 'maven', 'gradle'],
        'javascript': ['react', 'vue', 'angular', 'node.js'],
        'sql': ['mysql', 'postgresql', 'oracle', 'mongodb'],
        'aws': ['ec2', 's3', 'lambda', 'cloudformation']
    }
    
    return skill_map.get(skill.lower(), [])

def extract_relevant_experience(content: str, job_requirements: Dict[str, Any]) -> List[str]:
    """提取相关工作经验"""
    relevant_exp = []
    content_lower = content.lower()
    
    # 根据岗位要求的技能查找相关经验
    required_skills = job_requirements.get('required_skills', [])
    for skill in required_skills:
        skill_lower = skill.lower()
        sentences = content.split('.')
        for sentence in sentences:
            if skill_lower in sentence.lower() and ('project' in sentence.lower() or '项目' in sentence.lower()):
                relevant_exp.append(sentence.strip()[:150])
    
    return relevant_exp[:5]

def extract_industry_experience(content: str) -> List[str]:
    """提取行业经验"""
    industries = ['fintech', 'healthcare', 'ecommerce', 'education', 'gaming', 
                 '金融', '医疗', '电商', '教育', '游戏', '互联网']
    
    found_industries = []
    content_lower = content.lower()
    
    for industry in industries:
        if industry in content_lower:
            found_industries.append(industry)
    
    return found_industries

def extract_leadership_experience(content: str) -> Dict[str, Any]:
    """提取领导经验"""
    leadership_keywords = ['lead', 'manage', 'mentor', 'supervise', 'team lead', 
                          '领导', '管理', '带领', '指导', '团队负责人']
    
    leadership_exp = {
        'has_leadership': False,
        'team_size': 0,
        'leadership_roles': []
    }
    
    content_lower = content.lower()
    for keyword in leadership_keywords:
        if keyword in content_lower:
            leadership_exp['has_leadership'] = True
            
            # 尝试提取团队规模
            import re
            team_size_match = re.search(r'(\d+)\s*(?:people|person|members|团队|人)', content_lower)
            if team_size_match:
                leadership_exp['team_size'] = int(team_size_match.group(1))
    
    return leadership_exp

def assess_project_complexity(content: str) -> str:
    """评估项目复杂度"""
    complexity_indicators = {
        'high': ['distributed', 'microservices', 'scalable', 'enterprise', 'millions of users',
                '分布式', '微服务', '大型项目', '企业级'],
        'medium': ['full-stack', 'database', 'api', 'integration', '全栈', '数据库', '集成'],
        'low': ['simple', 'basic', 'small', '简单', '基础']
    }
    
    content_lower = content.lower()
    
    for level, indicators in complexity_indicators.items():
        for indicator in indicators:
            if indicator in content_lower:
                return level
    
    return 'medium'  # 默认中等复杂度

def analyze_career_progression(content: str) -> Dict[str, Any]:
    """分析职业发展轨迹"""
    progression = {
        'career_growth': False,
        'promotion_indicators': [],
        'skill_development': False
    }
    
    growth_keywords = ['promoted', 'senior', 'lead', 'manager', 'director',
                      '晋升', '提升', '高级', '资深', '主管']
    
    content_lower = content.lower()
    for keyword in growth_keywords:
        if keyword in content_lower:
            progression['career_growth'] = True
            progression['promotion_indicators'].append(keyword)
    
    return progression

def extract_degree_level(content: str, education: str) -> str:
    """提取学历水平"""
    content_combined = (content + " " + education).lower()
    
    if any(word in content_combined for word in ['phd', 'doctorate', 'ph.d', '博士']):
        return '博士'
    elif any(word in content_combined for word in ['master', 'mba', 'm.s', 'm.a', '硕士', '研究生']):
        return '硕士'
    elif any(word in content_combined for word in ['bachelor', 'b.s', 'b.a', '本科', '学士']):
        return '本科'
    elif any(word in content_combined for word in ['associate', 'diploma', '大专', '专科']):
        return '大专'
    else:
        return '本科'  # 默认

def extract_field_of_study(content: str) -> List[str]:
    """提取专业领域"""
    fields = ['computer science', 'software engineering', 'information technology',
             'computer engineering', 'mathematics', 'physics', 'statistics',
             '计算机科学', '软件工程', '信息技术', '计算机工程', '数学', '物理', '统计']
    
    found_fields = []
    content_lower = content.lower()
    
    for field in fields:
        if field in content_lower:
            found_fields.append(field)
    
    return found_fields

def assess_university_ranking(content: str) -> str:
    """评估大学排名"""
    top_universities = ['mit', 'stanford', 'harvard', 'cmu', 'berkeley', 
                       '清华', '北大', '上交', '复旦', '浙大']
    
    content_lower = content.lower()
    for uni in top_universities:
        if uni in content_lower:
            return 'top_tier'
    
    return 'regular'

def extract_relevant_courses(content: str, job_requirements: Dict[str, Any]) -> List[str]:
    """提取相关课程"""
    courses = []
    required_skills = job_requirements.get('required_skills', [])
    
    course_keywords = ['course', 'class', 'study', '课程', '学习']
    
    for skill in required_skills:
        for keyword in course_keywords:
            if skill.lower() in content.lower() and keyword in content.lower():
                courses.append(f"{skill}相关课程")
    
    return courses

def extract_certifications(content: str) -> List[str]:
    """提取认证信息"""
    cert_patterns = [
        r'certified\s+(\w+\s*\w*)',
        r'certification\s+in\s+(\w+\s*\w*)',
        r'(\w+)\s+certified',
        r'认证.*?(\w+)',
        r'(\w+).*?证书'
    ]
    
    certifications = []
    for pattern in cert_patterns:
        import re
        matches = re.findall(pattern, content, re.IGNORECASE)
        certifications.extend(matches)
    
    return certifications[:5]  # 最多5个

def assess_continuous_learning(content: str) -> bool:
    """评估持续学习能力"""
    learning_indicators = ['online course', 'training', 'workshop', 'conference',
                          'self-taught', 'bootcamp', '在线课程', '培训', '学习']
    
    content_lower = content.lower()
    return any(indicator in content_lower for indicator in learning_indicators)

def extract_academic_achievements(content: str) -> List[str]:
    """提取学术成就"""
    achievement_keywords = ['dean\'s list', 'honors', 'award', 'scholarship',
                           'publication', '荣誉', '奖学金', '论文', '获奖']
    
    achievements = []
    content_lower = content.lower()
    
    for keyword in achievement_keywords:
        if keyword in content_lower:
            achievements.append(keyword)
    
    return achievements

# 评估函数
def assess_technical_ability(candidate, content: str) -> float:
    """评估技术能力"""
    skills_count = len(candidate.skills) if isinstance(candidate.skills, list) else 1
    
    # 基于技能数量和项目经验
    base_score = min(80, skills_count * 8)
    
    # 基于项目复杂度加分
    complexity = assess_project_complexity(content)
    if complexity == 'high':
        base_score += 15
    elif complexity == 'medium':
        base_score += 10
    
    return min(100, base_score)

def assess_project_experience(content: str) -> float:
    """评估项目经验"""
    project_keywords = ['project', 'developed', 'built', 'created', '项目', '开发', '构建']
    
    count = sum(content.lower().count(keyword) for keyword in project_keywords)
    return min(90, count * 15)

def assess_communication_ability(content: str) -> float:
    """评估沟通能力"""
    # 基于简历质量评估
    communication_indicators = ['presentation', 'documentation', 'training', 'client',
                               '演示', '文档', '培训', '客户', '沟通']
    
    score = 60  # 基础分
    content_lower = content.lower()
    
    for indicator in communication_indicators:
        if indicator in content_lower:
            score += 8
    
    return min(95, score)

def assess_learning_ability(content: str) -> float:
    """评估学习能力"""
    learning_indicators = ['self-taught', 'learned', 'picked up', 'training',
                          'course', '自学', '学习', '掌握', '培训']
    
    base_score = 70
    content_lower = content.lower()
    
    for indicator in learning_indicators:
        if indicator in content_lower:
            base_score += 5
    
    # 技能多样性加分
    return min(100, base_score)

def assess_leadership_ability(content: str) -> float:
    """评估领导力"""
    leadership_exp = extract_leadership_experience(content)
    
    if leadership_exp['has_leadership']:
        base_score = 75
        if leadership_exp['team_size'] > 0:
            base_score += min(20, leadership_exp['team_size'] * 2)
        return min(95, base_score)
    else:
        return 40

def assess_industry_experience(content: str) -> float:
    """评估行业经验"""
    industries = extract_industry_experience(content)
    return min(85, len(industries) * 25 + 40)

def assess_education_background(candidate, content: str) -> float:
    """评估教育背景"""
    degree_scores = {
        '博士': 95,
        '硕士': 85,
        '本科': 75,
        '大专': 60
    }
    
    degree = extract_degree_level(content, getattr(candidate, 'education', ''))
    base_score = degree_scores.get(degree, 70)
    
    # 大学排名加分
    if assess_university_ranking(content) == 'top_tier':
        base_score += 10
    
    return min(100, base_score)

def assess_career_stability(content: str) -> float:
    """评估职业稳定性"""
    # 基于工作经验年限
    exp_years = extract_experience_years(content)
    
    if exp_years >= 5:
        return 85
    elif exp_years >= 3:
        return 75
    elif exp_years >= 1:
        return 65
    else:
        return 50

def extract_experience_years(content: str) -> int:
    """从内容中提取经验年限"""
    import re
    
    patterns = [
        r'(\d+)\s*(?:years?|年)\s*(?:experience|经验)',
        r'(?:experience|经验)[:\s]*(\d+)\s*(?:years?|年)'
    ]
    
    for pattern in patterns:
        match = re.search(pattern, content, re.IGNORECASE)
        if match:
            return int(match.group(1))
    
    return 0

def calculate_overall_skill_score(skill_analysis: Dict[str, Any]) -> float:
    """计算技能总分"""
    if 'error' in skill_analysis:
        return 0
    
    required_scores = [data['score'] for data in skill_analysis.get('required_match', {}).values()]
    preferred_scores = [data['score'] for data in skill_analysis.get('preferred_match', {}).values()]
    
    # 必需技能权重更高
    total_score = 0
    if required_scores:
        total_score += (sum(required_scores) / len(required_scores)) * 80
    
    if preferred_scores:
        total_score += (sum(preferred_scores) / len(preferred_scores)) * 20
    
    return min(100, total_score)

def calculate_experience_score(exp_analysis: Dict[str, Any], job_requirements: Dict[str, Any]) -> float:
    """计算经验分数"""
    if 'error' in exp_analysis:
        return 0
    
    total_years = exp_analysis.get('total_years', 0)
    required_years = exp_analysis.get('required_years', 0)
    
    if required_years == 0:
        return 85  # 无经验要求时的默认分数
    
    # 基础分数
    if total_years >= required_years:
        base_score = 80
        # 超额经验加分
        surplus = total_years - required_years
        base_score += min(15, surplus * 2)
    else:
        # 经验不足扣分
        base_score = (total_years / required_years) * 70
    
    # 相关经验加分
    relevant_exp = exp_analysis.get('relevant_experience', [])
    if relevant_exp:
        base_score += min(10, len(relevant_exp) * 2)
    
    return min(100, base_score)

def calculate_education_score(edu_analysis: Dict[str, Any]) -> float:
    """计算教育分数"""
    degree_scores = {
        '博士': 95,
        '硕士': 85,
        '本科': 75,
        '大专': 60
    }
    
    degree = edu_analysis.get('degree_level', '本科')
    base_score = degree_scores.get(degree, 70)
    
    # 认证加分
    certifications = edu_analysis.get('certifications', [])
    base_score += min(10, len(certifications) * 2)
    
    # 持续学习加分
    if edu_analysis.get('continuous_learning', False):
        base_score += 5
    
    return min(100, base_score)

def assess_soft_skills(content: str) -> float:
    """评估软技能"""
    soft_skill_indicators = ['communication', 'teamwork', 'problem solving', 'leadership',
                            'time management', '沟通', '团队合作', '解决问题', '领导力', '时间管理']
    
    base_score = 60
    content_lower = content.lower()
    
    for indicator in soft_skill_indicators:
        if indicator in content_lower:
            base_score += 6
    
    return min(90, base_score)

def generate_skill_suggestions(skill_analysis: Dict[str, Any]) -> List[str]:
    """生成技能改进建议"""
    suggestions = []
    
    missing_skills = skill_analysis.get('missing_skills', [])
    if missing_skills:
        suggestions.append(f"建议学习以下关键技能: {', '.join(missing_skills[:3])}")
    
    required_match = skill_analysis.get('required_match', {})
    for skill, data in required_match.items():
        if data['score'] < 0.5:
            suggestions.append(f"加强 {skill} 技能的项目实践经验")
    
    return suggestions

def generate_experience_suggestions(exp_analysis: Dict[str, Any]) -> List[str]:
    """生成经验改进建议"""
    suggestions = []
    
    experience_gap = exp_analysis.get('experience_gap', 0)
    if experience_gap > 0:
        suggestions.append(f"缺少 {experience_gap} 年相关工作经验，建议通过项目实践或实习补充")
    
    if not exp_analysis.get('leadership_experience', {}).get('has_leadership'):
        suggestions.append("建议积累团队领导或项目管理经验")
    
    return suggestions

def generate_education_suggestions(edu_analysis: Dict[str, Any]) -> List[str]:
    """生成教育改进建议"""
    suggestions = []
    
    if not edu_analysis.get('certifications'):
        suggestions.append("建议获得相关行业认证提升竞争力")
    
    if not edu_analysis.get('continuous_learning'):
        suggestions.append("建议参加在线课程或培训保持技能更新")
    
    return suggestions

def generate_analysis_summary(candidate, dimensions: List[AnalysisDimension], overall_score: float) -> str:
    """生成分析总结"""
    candidate_name = candidate.name or f"候选人_{candidate.id[:8]}"
    
    # 找出最强和最弱的维度
    best_dim = max(dimensions, key=lambda x: x.score)
    worst_dim = min(dimensions, key=lambda x: x.score)
    
    summary = f"""
{candidate_name} 的综合评分为 {overall_score:.1f} 分。

**优势分析:**
- {best_dim.name}: {best_dim.score:.1f}分，表现出色
- 总体技能掌握度较好，具备基本的岗位要求

**待改进方面:**
- {worst_dim.name}: {worst_dim.score:.1f}分，需要重点提升
- 建议在面试中重点考察相关能力

**适合度评估:**
{'非常适合' if overall_score >= 85 else '比较适合' if overall_score >= 70 else '基本适合' if overall_score >= 60 else '需要进一步评估'}该岗位，建议{'优先考虑' if overall_score >= 80 else '安排面试' if overall_score >= 65 else '谨慎考虑'}。
    """.strip()
    
    return summary

def generate_recommendations(dimensions: List[AnalysisDimension], overall_score: float) -> List[str]:
    """生成推荐建议"""
    recommendations = []
    
    if overall_score >= 85:
        recommendations.append("🌟 强烈推荐：候选人各方面能力优秀，建议优先安排面试")
    elif overall_score >= 70:
        recommendations.append("✅ 推荐面试：候选人整体符合要求，建议安排技术面试")
    elif overall_score >= 60:
        recommendations.append("⚠️ 谨慎考虑：候选人基本符合要求，但需要详细了解具体能力")
    else:
        recommendations.append("❌ 不推荐：候选人与岗位要求差距较大")
    
    # 基于各维度给出具体建议
    for dim in dimensions:
        if dim.score < 60:
            recommendations.append(f"📝 关注点：{dim.name}得分较低({dim.score:.1f}分)，面试时需要重点考察")
    
    return recommendations

def identify_risks(dimensions: List[AnalysisDimension], exp_analysis: Dict[str, Any]) -> List[str]:
    """识别潜在风险"""
    risks = []
    
    # 经验不足风险
    experience_gap = exp_analysis.get('experience_gap', 0)
    if experience_gap > 2:
        risks.append(f"⚠️ 经验风险：缺少 {experience_gap} 年相关经验，可能需要较长适应期")
    
    # 技能gap风险
    for dim in dimensions:
        if dim.name == "技能匹配" and dim.score < 50:
            risks.append("⚠️ 技能风险：核心技能匹配度不足，需要额外培训")
    
    # 稳定性风险
    stability_dim = next((d for d in dimensions if "稳定" in d.name), None)
    if stability_dim and stability_dim.score < 60:
        risks.append("⚠️ 稳定性风险：职业稳定性较低，可能存在跳槽风险")
    
    if not risks:
        risks.append("✅ 暂无明显风险点")
    
    return risks

def generate_interview_questions(dimensions: List[AnalysisDimension], job_requirements: Dict[str, Any]) -> List[str]:
    """生成面试问题"""
    questions = []
    
    # 基于薄弱环节生成问题
    weak_dimensions = [dim for dim in dimensions if dim.score < 70]
    
    for dim in weak_dimensions:
        if dim.name == "技能匹配":
            required_skills = job_requirements.get('required_skills', [])
            if required_skills:
                questions.append(f"请详细介绍您在 {required_skills[0]} 方面的项目经验")
        
        elif dim.name == "经验匹配":
            questions.append("请描述您最具挑战性的项目，以及您在其中承担的角色")
        
        elif dim.name == "软技能":
            questions.append("请举例说明您如何解决团队合作中的冲突")
    
    # 添加通用问题
    questions.extend([
        "您对这个岗位有什么期待？",
        "您认为自己最大的优势是什么？",
        "您如何保持技能的持续更新？"
    ])
    
    return questions[:8]  # 最多8个问题

# 全局工具列表
candidate_analysis_tools = [
    analyze_candidate_skills,
    analyze_candidate_experience,
    analyze_candidate_education,
    generate_candidate_radar_chart,
    generate_skill_comparison_chart,
    generate_comprehensive_analysis
]

if __name__ == "__main__":
    # 测试模块
    import asyncio
    
    async def test_analysis():
        # 初始化数据管理器
        data_manager.initialize()
        
        if data_manager.resumes:
            test_candidate_id = data_manager.resumes[0].id
            test_job_requirements = {
                'required_skills': ['Python', 'Django', 'MySQL'],
                'preferred_skills': ['Redis', 'Docker'],
                'min_experience_years': 3,
                'location': '北京'
            }
            
            print("🧪 测试候选人深度分析...")
            
            # 测试综合分析
            result = generate_comprehensive_analysis.invoke({
                "candidate_id": test_candidate_id,
                "job_id": None
            })
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
        else:
            print("❌ 无候选人数据进行测试")
    
    asyncio.run(test_analysis())



